/****************************************************************************
 * Copyright (C) 2012 Dj_Skual
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ****************************************************************************/
#include "UpdateDolTask.h"
#include "../../Controls/Application.h"
#include "../../Prompts/ProgressWindow.h"
#include "../../Prompts/PromptWindows.h"
#include "../../FileOperations/fileops.h"
#include "../FileDownloader.h"

UpdateDolTask::UpdateDolTask(const char * Url)
	: url(Url)
{
	result = false;
	running = true;
	
	ThreadedTaskHandler::Instance()->AddTask(this);
}

void UpdateDolTask::Execute(void)
{
	if(!CreateSubfolder(Settings.UpdatePath))
	{
		ShowError(tr("Could not create path: %s"), Settings.UpdatePath);
		running = false;
		return;
	}
	
	if(!NetworkInitPrompt())
	{
		ShowError(tr("Network is not initiated."));
		running = false;
		return;
	}
	
	if(ProgressWindow::Instance()->IsRunning())
		ProgressWindow::Instance()->SetTitle(tr("Updating boot.dol..."));
	else
		StartProgress(tr("Updating boot.dol..."));

	std::string tmpPath = Settings.UpdatePath;
	tmpPath += "/boot.tmp";
	
	if(DownloadFileToPath(url, tmpPath.c_str(), false) < 1024)
	{
		StopProgress();
		RemoveFile(tmpPath);
		ShowMsg(tr("Update failed"), tr("Could not download file."));
		running = false;
		return;
	}
	sleep(1);
	
	std::string dolPath = Settings.UpdatePath;
	dolPath += "/boot.dol";
	
	RemoveFile(dolPath);
	rename(tmpPath.c_str(), dolPath.c_str());
	
	result = true;
	running = false;
}
